#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/time.h>

#include "erpc.h"

void hello_helloworld(char *params)
{
    char *message = NULL;
    cJSON *response = NULL;
    cJSON *request = cJSON_CreateObject();
    if(NULL == request)
        return ;

    cJSON_AddStringToObject(request, "hello", params);
    if(0 != erpc_service_proxy_call("hello", "helloworld", request, &response, NULL))
    {
        cJSON_Delete(request);
        request = NULL;
        return ;
    }

    if(response)
    {
        message = cJSON_Print(response);
        printf("result: %s\n", message);
        free(message);
        cJSON_Delete(response);
    }
}

void *business(void *arg)
{
    while(1)
    {
        sleep(3);
        hello_helloworld("I'm helloworld app.");
    }
}

void hello_status_handler(cJSON *params)
{
    char *message = NULL;
    message = cJSON_Print(params);
    printf("status params: %s\n", message);
    free(message);
    cJSON_Delete(params);
}

pthread_t business_id;

int main(void)
{
    erpc_framework_init("app");

    erpc_observer_register("hello", "status", hello_status_handler, NULL);

    if(0 != pthread_create(&business_id, NULL, business, NULL))
        return -1;

    return erpc_framework_loop(ERPC_LOOP_DEFAULT);
}

